<?php

namespace catchAdmin\externalGoods\controller;

use catchAdmin\externalGoods\model\ManifestTemplate as ManifestTemplateModel;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use think\facade\Db;

class ManifestTemplate extends CatchAdmin
{
    protected $manifestTemplateModel;

    public function __construct(ManifestTemplateModel $manifestTemplateModel)
    {
        $this->manifestTemplateModel = $manifestTemplateModel;
    }

    /**
     * 获取模板列表
     */
    public function list(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->manifestTemplateModel->getList($user['tenant_id']);
        
        return CatchResponse::success([
            'list' => $list
        ]);
    }

    /**
     * 保存模板
     */
    public function save(Request $request, CatchAuth $auth)
    {
        $params = $request->post();
        if(empty($params['templateName'])) {
            return CatchResponse::fail('模板名称不能为空');
        }

        $user = $auth->user();
        
        // 检查模板名称是否重复
        $query = $this->manifestTemplateModel->where([
            'templateName' => $params['templateName'],
            'tenant_id' => $user['tenant_id'],
            'deleted_at' => 0  // 添加软删除条件
        ]);
        
        // 如果是更新操作，排除自身
        if(isset($params['id']) && !empty($params['id'])) {
            $query = $query->where('id', '<>', $params['id']);
        }
        
        $exists = $query->find();
        if($exists) {
            return CatchResponse::fail('模板名称已存在');
        }

        Db::startTrans();
        try {
            $params['tenant_id'] = $user['tenant_id'];
            $params['creator_id'] = $user['id'];
            
            if(isset($params['id']) && !empty($params['id'])) {
                // 更新前检查是否是自己的模板
                $template = $this->manifestTemplateModel->where([
                    'id' => $params['id'],
                    'deleted_at' => 0  // 添加软删除条件
                ])->find();
                
                if(!$template || $template['tenant_id'] != $user['tenant_id']) {
                    throw new \Exception('无权修改此模板');
                }
                
                // 更新
                $result = $this->manifestTemplateModel->update($params);
            } else {
                // 新增
                $result = $this->manifestTemplateModel->save($params);
            }
            
            if($result === false) {
                throw new \Exception('保存失败');
            }
            
            Db::commit();
            return CatchResponse::success([], '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return CatchResponse::fail($e->getMessage());
        }
    }

    /**
     * 删除模板
     */
    public function delete($id, CatchAuth $auth)
    {
        if(empty($id)) {
            return CatchResponse::fail('参数错误');
        }

        $user = $auth->user();
        
        Db::startTrans();
        try {
            // 检查是否是自己的模板
            $template = $this->manifestTemplateModel->where([
                'id' => $id,
                'deleted_at' => 0  // 添加软删除条件
            ])->find();
            
            if(!$template || $template['tenant_id'] != $user['tenant_id']) {
                throw new \Exception('无权删除此模板');
            }
            
            // 软删除
            $result = $this->manifestTemplateModel->destroy($id);
            
            if($result === false) {
                throw new \Exception('删除失败');
            }
            
            Db::commit();
            return CatchResponse::success([], '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return CatchResponse::fail($e->getMessage());
        }
    }
} 